<!-- 素材库-分组新增||修改 -->
<template>
  <a-modal
    :maskClosable="false"
    :title="title"
    centered
    :width="500"
    v-model="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
  >
    <a-form-model ref="ruleForm" :model="form" :rules="rules">
      <a-form-model-item
        v-if="visible && !form.id && treeDataLength > 1"
        :labelCol="{ span: 6 }"
        :wrapperCol="{ span: 18 }"
        label="上级分组"
        prop="parentId"
      >
        <GroupSelect v-model="form.parentId" :activeTabKey="activeTabKey" :maxLevel="3" />
      </a-form-model-item>
      <a-form-model-item :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }" label="分组名称" prop="name" class="disFlx">
        <a-input v-model="form.name" placeholder="请输入分组名称,最多20字符" :maxLength="20" style="flex:1;" />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { addWarehouseGroup, editWarehouseGroup } from '@/api/content/warehouse'
import GroupSelect from './groupSelect'

export default {
  components: {
    GroupSelect
  },
  props: {
    activeTabKey: {
      type: String,
      required: true,
      default: ''
    },
    treeDataLength: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      title: '新建分组',
      visible: false,
      confirmLoading: false,
      form: {
        id: undefined,
        parentId: undefined, // 上级ID
        name: ''
      },
      rules: {
        name: [{ required: true, message: '请输入分组名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    show(group) {
      const that = this
      Object.assign(that.$data, that.$options.data()) // 重置数据

      if (group && group.id) {
        that.title = '修改分组'
        that.form.id = group.id
        that.form.parentId = group.parentId
        that.form.name = group.name
      }

      that.visible = true
      that.$nextTick(() => {
        that.$refs.ruleForm.clearValidate()
      })
    },
    handleSubmit() {
      const that = this
      that.$refs.ruleForm.validate(async valid => {
        if (valid) {
          that.confirmLoading = true
          try {
            that.form.id
              ? await editWarehouseGroup(that.form)
              : await addWarehouseGroup({ ...that.form, type: that.activeTabKey })
            that.$message.success(that.form.id ? '已修改分组名称!' : '新增分组成功!')
            that.confirmLoading = false
            that.$emit('refresh')
            that.visible = false
          } catch (error) {
            that.confirmLoading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
